import { Module } from 'vuex'
import { ElMessage } from 'element-plus'
import { ILoginState } from './types'
import { IRootState } from '../types'

import { accountLogin, getUserById, getUserMenus } from '@/api/login/login'
import localCache from '@/utils/cache'
import { mapMenusToRoutes, menuMapToPermissions } from '@/utils/map-menus'
import router from '@/router'

const login: Module<ILoginState, IRootState> = {
  namespaced: true,
  state() {
    return {
      token: '',
      userInfo: {},
      userMenus: {},
      permissions: []
    }
  },
  getters: {},
  mutations: {
    saveToken(state, token: string) {
      state.token = token
    },
    saveUserInfo(state, userInfo: any) {
      userInfo.name = '管理员'
      state.userInfo = userInfo
    },
    saveUserMenus(state, userMenus: any) {
      state.userMenus = userMenus
      const routes = mapMenusToRoutes(userMenus)
      routes.forEach(route => {
        router.addRoute('main', route)
      })
      // 检查按钮的权限
      const permissions = menuMapToPermissions(userMenus)
      state.permissions = permissions
    }
  },
  actions: {
    // 登录请求
    async accountLoginAction( { commit, dispatch },   account: { name: string; password: string } ) {
      try {
        const loginResult = await accountLogin(account)
        if (loginResult) {
          const { id, token } = loginResult
          commit('saveToken', token)
          localCache.setCache('token', token)

          const userInfo = await getUserById(id)
          commit('saveUserInfo', userInfo)
          localCache.setCache('userInfo', userInfo)

          const userMenus = await getUserMenus(userInfo.role.id)
          commit('saveUserMenus', userMenus)
          localCache.setCache('userMenus', userMenus)

          dispatch('getInitalDataAction', null, { root: true })
          router.push('/main')
        } else {
          throw 'login error'
        }
      } catch (error) {
        ElMessage.error('账号或者密码错误')
      }
    },
    // 保存  token userinfo menu 到 store
    loadLocalCache({ commit, dispatch }) {
      const token = localCache.getCache('token')
      if (token) {
        commit('saveToken', token)
      }
      const userInfo = localCache.getCache('userInfo')
      if (userInfo) {
        commit('saveUserInfo', userInfo)
      }
      const userMenus = localCache.getCache('userMenus')
      if (userMenus) {
        commit('saveUserMenus', userMenus)
      }
    }
  }
}

export default login
